package com.example.securityconfiggen.controller;

import com.example.securityconfiggen.util.KeyGeneratorUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 密钥生成控制器，提供密钥生成相关的API和页面
 */
@Controller
@RequestMapping
public class KeyGeneratorController {

    /**
     * 显示密钥生成器页面
     *
     * @return 密钥生成器模板页面
     */
    @GetMapping("/keygen")
    public String showKeyGenPage() {
        return "keygen";
    }

    /**
     * 生成AES-256密钥
     *
     * @return AES密钥信息
     */
    @GetMapping("/api/keygen/aes")
    @ResponseBody
    public ResponseEntity<Map<String, String>> generateAesKey() {
        try {
            String aesKey = KeyGeneratorUtil.generateAesKey();
            Map<String, String> result = new HashMap<>();
            result.put("algorithm", "AES-256");
            result.put("key", aesKey);
            result.put("format", "Base64");
            return ResponseEntity.ok(result);
        } catch (NoSuchAlgorithmException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "生成AES密钥失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(error);
        }
    }

    /**
     * 生成SHA-256哈希
     *
     * @param seed 用于生成哈希的种子（可选）
     * @return SHA-256哈希信息
     */
    @GetMapping("/api/keygen/sha256")
    @ResponseBody
    public ResponseEntity<Map<String, String>> generateSha256Hash(
            @RequestParam(required = false) String seed) {
        try {
            // 如果未提供种子，则生成一个随机种子
            if (seed == null || seed.isEmpty()) {
                seed = Long.toString(System.currentTimeMillis()) + Math.random();
            }
            
            String sha256Hash = KeyGeneratorUtil.generateSha256Hash(seed);
            Map<String, String> result = new HashMap<>();
            result.put("algorithm", "SHA-256");
            result.put("hash", sha256Hash);
            result.put("format", "Hex");
            result.put("seed", seed);
            return ResponseEntity.ok(result);
        } catch (NoSuchAlgorithmException e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "生成SHA-256哈希失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(error);
        }
    }

    /**
     * 生成HMAC SHA-256密钥
     *
     * @param keySize 密钥大小（字节数），默认为32
     * @return HMAC SHA-256密钥信息
     */
    @GetMapping("/api/keygen/hmac")
    @ResponseBody
    public ResponseEntity<Map<String, String>> generateHmacKey(
            @RequestParam(defaultValue = "32") int keySize) {
        
        // 限制密钥大小在合理范围内
        if (keySize < 16) keySize = 16;
        if (keySize > 64) keySize = 64;
        
        String hmacKey = KeyGeneratorUtil.generateHmacSha256Key(keySize);
        Map<String, String> result = new HashMap<>();
        result.put("algorithm", "HMAC-SHA-256");
        result.put("key", hmacKey);
        result.put("format", "Base64");
        result.put("keySizeBytes", String.valueOf(keySize));
        result.put("keySizeBits", String.valueOf(keySize * 8));
        return ResponseEntity.ok(result);
    }

    /**
     * 生成所有类型的密钥
     *
     * @return 包含所有密钥类型的信息
     */
    @GetMapping("/api/keygen/all")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> generateAllKeys() {
        try {
            Map<String, String> keys = KeyGeneratorUtil.generateAllKeys();
            
            // 创建结构化响应
            Map<String, Object> result = new HashMap<>();
            
            Map<String, Object> aes = new HashMap<>();
            aes.put("algorithm", "AES-256");
            aes.put("key", keys.get("aesKey"));
            aes.put("format", "Base64");
            
            Map<String, Object> hmac = new HashMap<>();
            hmac.put("algorithm", "HMAC-SHA-256");
            hmac.put("key", keys.get("hmacKey"));
            hmac.put("format", "Base64");
            hmac.put("keySizeBytes", "32");
            hmac.put("keySizeBits", "256");
            
            Map<String, Object> sha = new HashMap<>();
            sha.put("algorithm", "SHA-256");
            sha.put("hash", keys.get("sha256Hash"));
            sha.put("format", "Hex");
            
            result.put("aes", aes);
            result.put("hmac", hmac);
            result.put("sha256", sha);
            
            return ResponseEntity.ok(result);
        } catch (NoSuchAlgorithmException e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "生成密钥失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(error);
        }
    }
} 